import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, anyRoutes, asyncRoutes, constantRoutes } from '@/router'
import router from '@/router'

const getDefaultState = () => {
    return {
        token: getToken(),
        name: localStorage.getItem('userName'),
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    CLEAR(state) {
        state.name = {},
            localStorage.removeItem('userName')
    }
}

const actions = {
    // user login
    async login({ commit }, userInfo) {
        const { username, password } = userInfo
        let res = await login({ name: username.trim(), password: password })
        if (res.code == 200) {
            commit('SET_NAME', res.data[0].name)
            localStorage.setItem('userName', res.data[0].name)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}